import { defineStore } from 'pinia';
import { removeTokens, setRefreshTokenAtStorage, setTokenAtStorage } from '@/utils/tokens.js';
import LoginApi from '@/api/login_mock.js';
import UserApi from "@/api/user_mock.js";

// 定义一个name为‘userStore’的store
export const useUserStore = defineStore('userStore', {
    // 第三方插件的持久化配置
    persist: {
        enabled: true,
        strategies: [{
            storage: localStorage
        }]
    },
    state: () => {
        return {
            // 用户信息
            userInfo: {},
            // 用户权限信息
            permissions: {},
            isLogin: false,
        }
    },
    actions: {
        /**
         * 用户注册
         */
        async register(username: string, password: string, contact: string, code: string): Promise<any> {
            console.debug("request register api ...", username, password, code);

            const data = {
                username: username,
                password: window.btoa(password), // base64编码
                code: code
            };
            // 只能是邮箱或手机号
            if (contact.indexOf("@") > 0) {
                data.email = contact;
            } else {
                data.phone = contact;
            }
            // 发送注册请求
            return await LoginApi.signUp(data);
        },
        /**
         * 用户登录
         */
        async logIn(account: string, password: string, verifyCode: string): Promise<any> {
            // 发送登录请求
            const resp = await LoginApi.logIn(account, window.btoa(password), verifyCode);

            // 存储token
            const token = resp.data.access_token;
            const refreshToken = resp.data.refresh_token;

            setTokenAtStorage(token);
            setRefreshTokenAtStorage(refreshToken);

            // 存储用户信息
            this.saveUserInfo(resp.data.userInfo);
            return {
                accessToken: token,
                refreshToken: refreshToken,
                userId: resp.data.userInfo.id
            }
        },
        /**
         * 退出登录
         */
        async logOut(): Promise<void> {
            // 发送登录请求
            await LoginApi.logOut();
            this.clearUser();
        },

        /**
         * 根据ID，查询user
         * @param userId
         * @returns {Promise<*>}
         */
        async findUserById(userId: number): Promise<UserInfo> {
            const resp = await UserApi.findUserById(userId);
            const user = resp.data;
            user.userId = user.uid;
            return user;
        },

        /**
         * 保存登录用户信息
         */
        saveUserInfo(data: any): void {
            this.isLogin = true;
            this.userInfo = {
                uid: data.id,
                username: data.username,
                nickname: data.nickname,
                avatarUrl: data.avatarUrl,
                roles: 'ROLE_USER'
            };
        },
        /**
         * 清除登录用户信息
         */
        clearUser(): void {
            console.debug("clearUser ... ");
            this.userInfo = {} as UserInfo;
            this.permissions = {} as Permissions;
            this.isLogin = false;

            removeTokens();
        }
    }
});

